<?php
namespace App\Plugins\Shh\Services;

use App\EmptyObject;
use App\Models\Project;
use App\Plugins\Shh\DB;
use App\Services\Repo\ProjectRepo;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Pagination\LengthAwarePaginator;

class ProjectService extends ProjectRepo
{
    public function update(array $_filter, array $_update_data):bool
    {
        //保存实惠插件数据
        if (!empty($_update_data['shihui'])) {
            $_update_data['plugins']['shihui'] = $_update_data['shihui'];
        }
        return parent::update($_filter, $_update_data);
    }

    public function read($limit = 0)
    {
        $shh_db = DB::createDb('plugin_shh', 'customers');
        $projects = parent::read();
        //添加未审核人数
        $shh_key = [];
        foreach ($projects as $project) {
            if (!$project->plugins instanceof EmptyObject
                && isset($project->plugins['shihui'])
                && isset($project->plugins['shihui']['key'])) {
                array_push($shh_key, $project->plugins['shihui']['key']);
            }
        }
        if ($shh_key) {
            $count = $shh_db->aggregate([
                [
                    '$match' => [
                        'shhKey' => [ '$in' => $shh_key ],
                        '_v' => 0
                    ]
                ], [
                    '$group' => [
                        '_id' => '$shhKey',
                        'count' =>['$sum' => 1]
                    ]
                ]
            ]);
            $shh_key = [];
            foreach ($count as $value) {
                $shh_key[$value['_id']] = $value['count'];
            }
            $items = $projects->map(function ($project) use ($shh_key) {
                if (isset($project['community']['key'])) {
                    $project->wvCount = $shh_key[$project['community']['key']] ?? 0;
                    return $project;
                }  else {
                    return $project;
                }
            });
            $projects = new LengthAwarePaginator($items,
                $projects->total(), 20, request()->input('page', 1));
        }
        return $projects;
    }
}